package net.dasviertel.buddylockscreen.activities;

import net.dasviertel.buddylockscreen.application.AppPreferences;
import net.dasviertel.buddylockscreen.data.Calculator;
import net.dasviertel.buddylockscreen.data.ContactsDataManager;
import net.dasviertel.buddylockscreen.data.ContactsObject;
import net.dasviertel.buddylockscreen.services.LocalService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.Contacts;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.monitorcontactschanges.R;

public class MainActivity extends Activity {

	private static final int CONTACT_PICKER_RESULT = 1;

	private static final int SELECT_IMAGE_RESULT = 2;

	private Button selectContactButton, selectPhoneButton, selectImageButton, startServiceButton, stopServiceButton, placeInfosButton;

	private TextView selectedContactTextView, selectedNumberTextView;	
	
	private ImageView selectedImage;

	private LocalService localService;	
	
	public LocalService getLocalService() {
		return localService;
	}

	public void setLocalService(LocalService localService) {
		this.localService = localService;
	}

	private boolean isBound = false;

	private Bitmap bitmap;

	@Override
	protected void onDestroy() {
		super.onDestroy();
		doUnbindService();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		ContactsDataManager.getInstance().init();

		selectContactButton = (Button) findViewById(R.id.bt_select_contact);
		selectImageButton = (Button) findViewById(R.id.bt_select_image);
		selectPhoneButton = (Button) findViewById(R.id.bt_select_phone_number);
		startServiceButton = (Button) findViewById(R.id.bt_start_service);
		stopServiceButton = (Button) findViewById(R.id.bt_stop_service);
		
		placeInfosButton = (Button) findViewById(R.id.bt_place_contact_info_on_image);
		selectedImage = (ImageView) findViewById(R.id.iv_selected_image_preview);
		selectedContactTextView = (TextView) findViewById(R.id.tv_selected_contact);
		selectedNumberTextView = (TextView) findViewById(R.id.tv_selected_phone_number);

		selectedContactTextView.setText(AppPreferences.getInstance().getContactName());
		selectedNumberTextView.setText(AppPreferences.getInstance().getContactPhoneNumber());

		selectContactButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
				startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);

			}
		});

		selectPhoneButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent choosePhoneActivityIntent = new Intent(getApplicationContext(), ChoosePhoneActivity.class);
				startActivity(choosePhoneActivityIntent);

			}
		});

		selectImageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_IMAGE_RESULT);

			}
		});

		placeInfosButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(getApplicationContext(), CreateImageActivity.class);
				startActivity(intent);

			}
		});

		
		startServiceButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stopServiceButton.setVisibility(View.VISIBLE);
				
				doBindService();
				startServiceButton.setVisibility(View.GONE);

			}
		});

		stopServiceButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stopServiceButton.setVisibility(View.GONE);
				doUnbindService();
				startServiceButton.setVisibility(View.VISIBLE);

			}
		});
	
	}

	@Override
	protected void onResume() {
		super.onResume();

		selectedNumberTextView.setText(AppPreferences.getInstance().getContactPhoneNumber());

		Calculator.getInstance();
		selectedImage.setImageBitmap(Calculator.decodeSampledBitmapFromFile(AppPreferences.getInstance().getImageNameAndPath(), 100, 100));

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {

			localService = ((LocalService.LocalBinder) service).getService();

			Log.i("", "Local Service connected");
		}

		public void onServiceDisconnected(ComponentName className) {

			localService = null;

		}
	};

	void doBindService() {

		Intent intent = new Intent(getApplicationContext(), LocalService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

		isBound = true;

	}

	void doUnbindService() {		
		if (isBound) {
			unbindService(mConnection);
		}
		isBound = false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == CONTACT_PICKER_RESULT) {
			if (resultCode == RESULT_OK) {			
				Uri result = data.getData();
				String id = result.getLastPathSegment();
				
				ContactsObject contactsObject = ContactsDataManager.getInstance().getContactById(id);
				
				AppPreferences.getInstance().setNewContactId(id);
				AppPreferences.getInstance().setContactName(contactsObject.getName());
				AppPreferences.getInstance().setNewContactPhoneNumber(getResources().getString(R.string.not_selected_yet));

				selectedContactTextView.setText(AppPreferences.getInstance().getContactName());
				selectedNumberTextView.setText(AppPreferences.getInstance().getContactPhoneNumber());

			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == SELECT_IMAGE_RESULT) {

			if (resultCode == RESULT_OK) {
				Uri selectedImageUri = data.getData();
				String[] projection = { MediaStore.Images.Media.DATA };
				Cursor cursor = this.getContentResolver().query(selectedImageUri, projection, null, null, null);
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				String fpath = cursor.getString(column_index);
				AppPreferences.getInstance().setNewImageNameAndPath(fpath);

				Calculator.getInstance();
				selectedImage.setImageBitmap(Calculator.decodeSampledBitmapFromFile(fpath, 100, 100));
			}

			if (resultCode == RESULT_CANCELED) {

			}

		}

	}

	@Override
	protected void onPause() {
		super.onPause();

		if (bitmap != null) {
			bitmap.recycle();
			bitmap = null;
		}

	}

}
